package com.albert.View;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class IOSSwitch extends View {

    private Paint paint;
    private boolean isOn = false;
    private float radius, switchWidth, switchHeight;
    private float thumbX;
    private int switchColorOn = Color.parseColor("#4cd964"); // iOS绿色
    private int switchColorOff = Color.parseColor("#e5e5ea"); // 灰色
    private int thumbColor = Color.WHITE;

    public IOSSwitch(Context context) {
        super(context);
        init();
    }

    public IOSSwitch(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        switchWidth = w;
        switchHeight = h;
        radius = switchHeight / 2;
        thumbX = isOn ? switchWidth - radius : radius;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 绘制背景
        paint.setColor(isOn ? switchColorOn : switchColorOff);
        canvas.drawRoundRect(0, 0, switchWidth, switchHeight, radius, radius, paint);

        // 绘制滑块
        paint.setColor(thumbColor);
        canvas.drawCircle(thumbX, switchHeight / 2, radius - 4, paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            toggle();
            // 手动触发点击回调
            performClick();
        }
        return true;
    }
    // 重写 performClick
    @Override
    public boolean performClick() {
        super.performClick();
        return true;
    }
    private void toggle() {
        final float start = thumbX;
        final float end = isOn ? radius : switchWidth - radius;
        ValueAnimator animator = ValueAnimator.ofFloat(start, end);
        animator.setDuration(200);
        animator.addUpdateListener(animation -> {
            thumbX = (float) animation.getAnimatedValue();
            invalidate();
        });
        animator.start();
        isOn = !isOn;
    }

    public boolean isOn() {
        return isOn;
    }

    public void setOn(boolean on) {
        isOn = on;
        thumbX = isOn ? switchWidth - radius : radius;
        invalidate();
    }
}
